import os
import json
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from django.conf import settings
from .judger import create_judger, JudgeResult
from .security import SecurityManager


# Django模型（示例）
class Submission:
    """
    提交模型（示例）
    在实际Django项目中，这应该是一个Django模型
    """
    def __init__(self, id, executable_path, input_data, expected_output):
        self.id = id
        self.executable_path = executable_path
        self.input_data = input_data
        self.expected_output = expected_output


# Django视图函数
@csrf_exempt
@require_http_methods(["POST"])
def judge_submission(request):
    """
    判题视图函数
    
    :param request: Django HTTP请求对象
    :return: JSON响应
    """
    try:
        # 解析请求数据
        data = json.loads(request.body)
        submission_id = data.get('submission_id')
        executable_path = data.get('executable_path')
        input_data = data.get('input_data', '')
        expected_output = data.get('expected_output', '')
        time_limit = data.get('time_limit', 1000)
        memory_limit = data.get('memory_limit', 65536)
        
        # 验证必要参数
        if not submission_id or not executable_path:
            return JsonResponse({
                'error': 'Missing required parameters'
            }, status=400)
        
        # 创建判断器
        judger = create_judger(time_limit, memory_limit)
        
        # 安全检查和沙箱运行
        if not os.path.exists(executable_path):
            return JsonResponse({
                'error': 'Executable file not found'
            }, status=400)
        
        # 在沙箱中运行程序
        with SecurityManager() as security_manager:
            # 验证可执行文件
            if not security_manager.validate_executable(executable_path):
                return JsonResponse({
                    'result': JudgeResult.SYSTEM_ERROR.value,
                    'message': 'Invalid executable file'
                })
            
            # 创建沙箱副本
            sandboxed_executable = security_manager.create_sandboxed_copy(executable_path)
            
            # 执行判断
            result = judger.judge(sandboxed_executable, input_data, expected_output)
        
        # 返回结果
        return JsonResponse({
            'submission_id': submission_id,
            'result': result
        })
    
    except json.JSONDecodeError:
        return JsonResponse({
            'error': 'Invalid JSON data'
        }, status=400)
    
    except Exception as e:
        return JsonResponse({
            'error': f'Internal server error: {str(e)}'
        }, status=500)


# Django管理命令（示例）
def judge_from_model(submission_id):
    """
    从模型对象进行判题（示例）
    
    :param submission_id: 提交ID
    :return: 判题结果
    """
    # 在实际Django项目中，这里应该从数据库获取提交对象
    # submission = Submission.objects.get(id=submission_id)
    
    # 示例数据
    submission = Submission(
        id=submission_id,
        executable_path="/path/to/executable",
        input_data="sample input",
        expected_output="expected output"
    )
    
    # 创建判断器
    judger = create_judger()
    
    # 安全检查和沙箱运行
    with SecurityManager() as security_manager:
        # 验证可执行文件
        if not security_manager.validate_executable(submission.executable_path):
            return {
                'result': JudgeResult.SYSTEM_ERROR.value,
                'message': 'Invalid executable file'
            }
        
        # 创建沙箱副本
        sandboxed_executable = security_manager.create_sandboxed_copy(submission.executable_path)
        
        # 执行判断
        result = judger.judge(
            sandboxed_executable,
            submission.input_data,
            submission.expected_output
        )
    
    return result


# 配置示例
class OJConfig:
    """
    OJ系统配置
    """
    def __init__(self):
        self.time_limit = getattr(settings, 'OJ_TIME_LIMIT', 1000)
        self.memory_limit = getattr(settings, 'OJ_MEMORY_LIMIT', 65536)
        self.sandbox_dir = getattr(settings, 'OJ_SANDBOX_DIR', None)
